// See the License for the specific language governing permissions and
// limitations under the License.

import { Button, message } from 'antd';
import React, { useContext, useState } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { useAsyncEffect } from 'ahooks';

import NotFound from '../../NotFound';

import { storage } from '@/utils/Storage';
import { GlobalUserInfo } from '@/layout/BasicLayout';

// 定义 Permission 组件
const Permission: React.FC<{
  children: React.ReactNode;
  name?: string;
  permissionObj?: {
    isPagePermission?: boolean | undefined;
    isToken?: boolean | undefined;
  } & boolean;
}> = ({ children, name, permissionObj }) => {
  // 使用 useState 钩子定义 isAuth 和 setIsAuth
  const globalUserInfoContext = useContext(GlobalUserInfo);
  const [isAuth, setIsAuth] = useState<boolean | undefined>(undefined);
  useAsyncEffect(async () => {
    setIsAuth(!!globalUserInfoContext?.menus?.map((item) => item?.title)?.includes(name));
  }, [globalUserInfoContext, window.location.pathname]);

  // 如果 isAuth 未定义，显示错误信息
  if (isAuth === undefined) {
    message.error('Permission is not defined');
  }

  // 如果页面权限不足，返回 403 错误页面
  if ((permissionObj === true || permissionObj?.isPagePermission) && isAuth === false) {
    return (
      <NotFound
        status={403}
        title="403权限不足"
        subTitle="对不起！暂无该页面访问权限！请联系管理员分配权限或更换账号登录"
        extra={
          <>
            <Button type="primary">
              <Link to="/login">重新登录</Link>
            </Button>
          </>
        }
      />
    );
  }

  // 获取本地存储中的 token
  const token = storage.get('token');

  // 如果需要 token 并且 token 存在，返回子组件
  if ((permissionObj === true || permissionObj?.isToken) && token) {
    return children;
  }

  // 如果 token 不存在，显示错误信息并重定向到登录页面
  message.error('token 不存在');

  return <Navigate replace to="/login" />;
};

export default Permission;
